﻿using System;
using Microsoft.Practices.ServiceLocation;
using Topshelf.ServiceConfigurators;

namespace Topshelf.CommonService
{
    public static class ServiceConfiguratorExtensions
    {
        #region Public Methods and Operators


        public static ServiceConfigurator<T> ConstructUsingServiceLocatorContainer<T>(this ServiceConfigurator<T> configurator) where T : class
        {
            configurator.ConstructUsing(serviceFactory =>
            {
                T service;

                try
                {
                    service = (T)ServiceLocator.Current.GetService(typeof(T));
                }
                catch (NullReferenceException ex)
                {
                    throw new NullReferenceException(
                        "ServiceLocator has not been initialized; " + "I was trying to retrieve " + typeof(T),
                        ex);
                }
                catch (ActivationException ex)
                {
                    throw new ActivationException(
                        "The needed dependency of type " + typeof(T).Name +
                        " could not be located with the ServiceLocator. You'll need to register it with " +
                        "the Common Service Locator (CSL) via your IoC's CSL adapter. " + ex.Message, ex);
                }

                return service;
            });

            return configurator;
        }


        #endregion
    }
}